package vip.meeet.lifecycle;

import cn.freemethod.mock.DBMock;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * postConstruct  @PostConstruct
 * afterPropertiesSet(和Spring的耦合度比init-method高)
 * init-method(必须无参)(反射实现，效率比afterPropertiesSet低)
 * org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods
 *
 *	AbstractApplicationContext#refresh
 */
public class LifeCycleBean implements InitializingBean,BeanNameAware,BeanFactoryAware,ApplicationContextAware,DisposableBean {
	
	private static final String thisClassName = LifeCycleBean.class.getName();
	
	static final AtomicInteger sequence = new AtomicInteger(1);
	
	@Resource
	private DBMock dbMock;
	
	private String config;
	
	public LifeCycleBean(){
//		this.config = dbMock.mockGet();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		String thisClassName = InitializingBean.class.getName();
		System.out.println(sequence.getAndIncrement() + " " + thisClassName + "#"  + "afterPropertiesSet");
	}
	
	public void initMethod(){
		System.out.println(sequence.getAndIncrement() + " " + thisClassName + "#"  + "initMethod");
	}

	@Override
	public void destroy() throws Exception {
		String thisClassName = DisposableBean.class.getName();
		System.out.println(sequence.getAndIncrement() + " " + thisClassName + "#"  + "destroy");
		
	}

	@Override
	public void setBeanName(String name) {
		String thisClassName = BeanNameAware.class.getName();
		System.out.println(sequence.getAndIncrement() + " " + thisClassName + "#"  + "setBeanName");
		
	}
	
	public void destoryMethod(){
		System.out.println(sequence.getAndIncrement() + " " + thisClassName + "#"  + "destoryMethod");
	}
	
	@PostConstruct
	public void postConstruct(){
		System.out.println(sequence.getAndIncrement() + " " + thisClassName + "#"  + "postConstruct");
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		String thisClassName = BeanFactoryAware.class.getName();
		System.out.println(sequence.getAndIncrement() + " " + thisClassName + "#"  + "setBeanFactory");
//		System.out.println("  " + beanFactory.getClass().getName());
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		String thisClassName = ApplicationContextAware.class.getName();
		System.out.println(sequence.getAndIncrement() + " " + thisClassName + "#"  + "setApplicationContext");
//		System.out.println("  " + applicationContext.getClass().getName());
	}

	public String getConfig() {
		return config;
	}

}
